<template>
  <div>
    <el-breadcrumb separator="/">
      <el-breadcrumb-item :to="{ path: '/welcome' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>资产管理</el-breadcrumb-item>
      <el-breadcrumb-item>型号配置</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card>
      <el-tabs value="models" @tab-click="handleClickTab">
        <el-tab-pane label="型号列表" name="models">
          <el-form :inline="true" :model="addModelForm" label-position="right" label-width="80px" :rules="addModelFormRules" ref="addModelFormRef" size="small">
            <el-form-item label="上级分类" prop="parent_id">
              <el-cascader v-model="addModelForm.parent_id" :options="modelsListData" :props="selectModelProps" clearable @change="selectModelValueChange"></el-cascader>
            </el-form-item>
            <el-form-item label="型号名称" prop="model_name">
              <el-input v-model="addModelForm.model_name"></el-input>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="addModel">添加</el-button>
              <el-button type="warning" @click="resetForm">重置</el-button>
            </el-form-item>
          </el-form>
          <el-divider></el-divider>
          <el-table :data="modelsListData" border row-key="id" stripe style="width: 100%" size="mini">
            <el-table-column prop="model_name" label="分类名称" width="150" align="left" header-align="center"></el-table-column>
            <el-table-column label="操作" width="150" align="center">
              <template slot-scope="scope">
                <el-button @click="editModel(scope.row)" type="primary" size="mini" class="tableRowButton">编辑</el-button>
                <el-popover placement="top" width="80" :ref="`popover-${scope.$index}`">
                  <p>
                    确定要删除分类 <b>{{ scope.row.model_name }}</b> 吗？
                  </p>
                  <div style="text-align: right; margin: 0">
                    <el-button size="mini" type="text" @click="cancelAction(scope)">取消</el-button>
                    <el-button type="primary" @click="delModel(scope)" size="mini">确定</el-button>
                  </div>
                  <el-button slot="reference" type="danger" size="mini">删除</el-button>
                </el-popover>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
        <el-tab-pane label="配置管理" name="parameter">
          <el-button type="primary" size="mini" @click="addParaDialog">新配置</el-button>
          <el-divider></el-divider>
          <el-table :data="parameterListData" border stripe style="width: 100%" size="mini">
            <el-table-column prop="cpu" label="cpu" width="100" align="left" sortable header-align="center"></el-table-column>
            <el-table-column prop="mem" label="内存" width="80" align="left" sortable header-align="center"></el-table-column>
            <el-table-column prop="disk" label="硬盘" width="100" align="left" sortable header-align="center"></el-table-column>
            <el-table-column prop="screen" label="屏幕" width="100" align="left" sortable header-align="center"></el-table-column>
            <el-table-column prop="gpu" label="显卡" width="100" align="left" sortable header-align="center"></el-table-column>
            <el-table-column prop="price" label="价格" width="110" align="left" sortable header-align="center"></el-table-column>
            <el-table-column prop="suggest_ug" label="建议使用人群" width="150" align="left" header-align="center"></el-table-column>
            <el-table-column prop="remarks" label="备注" width="100" align="left" header-align="center"></el-table-column>
            <el-table-column label="操作" width="150" align="center">
              <template slot-scope="scope">
                <el-button @click="editPara(scope.row)" type="primary" size="mini" class="tableRowButton">编辑</el-button>
                <el-popover placement="top" width="80" :ref="`popover-${scope.$index}`">
                  <p>
                    确定要删除配置 <b>{{ scope.row.cpu }}</b> 吗？
                  </p>
                  <div style="text-align: right; margin: 0">
                    <el-button size="mini" type="text" @click="cancelAction(scope)">取消</el-button>
                    <el-button type="primary" @click="delPara(scope)" size="mini">确定</el-button>
                  </div>
                  <el-button slot="reference" type="danger" size="mini">删除</el-button>
                </el-popover>
              </template>
            </el-table-column>
          </el-table>
          <el-pagination
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page="queryParaInfo.pagenum"
            :page-sizes="[10, 20, 50]"
            :page-size="queryParaInfo.pagesize"
            layout="total, sizes, prev, pager, next, jumper"
            :total="paraListTotal"
          >
          </el-pagination>
        </el-tab-pane>
      </el-tabs>
    </el-card>
    <el-dialog title="编辑分类" :visible.sync="dialogModelEditFormVisible">
      <el-form :model="modelEditForm" size="small" label-width="80px" label-position="right">
        <el-form-item label="分类名称">
          <el-input v-model="modelEditForm.model_name" autocomplete="off"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="editSaveModel" size="small">保 存</el-button>
        <el-button @click="dialogModelEditFormVisible = false" size="small">取 消</el-button>
      </div>
    </el-dialog>
    <!-- 添加配置 对话框 -->
    <el-dialog title="新增配置" :visible.sync="dialogAddParaFormVisible" class="dialog_padding">
      <el-form :model="addParaForm" :rules="addParaFormRules" ref="addParaFormRef" size="small" label-width="80px" label-position="right">
        <el-form-item label="型号" prop="model_id">
          <el-cascader
            ref="addParaCascader"
            style="display: block"
            v-model="selectModelValue2"
            :options="modelsListData"
            :props="selectModelProps2"
            clearable
            @change="selectModelValueChange2"
          ></el-cascader>
        </el-form-item>
        <el-form-item label="CPU" prop="cpu">
          <el-input v-model="addParaForm.cpu" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="内存" prop="mem">
          <el-input v-model="addParaForm.mem" autocomplete="on"></el-input>
        </el-form-item>
        <el-form-item label="硬盘" prop="disk">
          <el-input v-model="addParaForm.disk" autocomplete="on"></el-input>
        </el-form-item>
        <el-form-item label="显卡" prop="gpu">
          <el-input v-model="addParaForm.gpu" autocomplete="on"></el-input>
        </el-form-item>
        <el-form-item label="屏幕" prop="screen">
          <el-input v-model="addParaForm.screen" autocomplete="on"></el-input>
        </el-form-item>
        <el-form-item label="价格" prop="price">
          <el-input v-model="addParaForm.price" autocomplete="on"></el-input>
        </el-form-item>
        <el-form-item label="建议使用人群" prop="suggest_ug">
          <el-input v-model="addParaForm.suggest_ug" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="备注" prop="remarks">
          <el-input v-model="addParaForm.remarks" autocomplete="off"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="addPara" size="small">保 存</el-button>
        <el-button @click="dialogAddParaFormVisible = false" size="small">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    return {
      addModelForm: {
        parent_id: 0,
        model_name: ''
      },
      addModelFormRules: {
        parent_id: [],
        model_name: [
          { max: 17, message: '长度不大于17个字符', trigger: 'blur' },
          { required: true, message: '请填写型号名称', trigger: 'blur' }
        ]
      },
      modelsListData: [],
      total: 0,
      modelEditForm: {},
      idArr: [],
      selectModelProps: {
        label: 'model_name',
        value: 'id',
        checkStrictly: true,
        emitPath: false
      },
      selectModelProps2: {
        label: 'model_name',
        value: 'id',
        emitPath: true
      },
      dialogModelEditFormVisible: false,
      parameterListData: [],
      paraListTotal: 0,
      queryParaInfo: {
        pagenum: 1,
        pagesize: 10
      },
      dialogAddParaFormVisible: false,
      selectModelValue2: [],
      addParaForm: {},
      addParaFormRules: {
        model_id: [
          { required: true, message: '请输入cpu型号', trigger: 'blur' },
          { max: 255, message: '长度不大于255个字符', trigger: 'blur' }
        ],
        cpu: [
          { required: true, message: '请输入cpu型号', trigger: 'blur' },
          { max: 255, message: '长度不大于255个字符', trigger: 'blur' }
        ],
        mem: [
          { required: true, message: '请输入内存大小', trigger: 'blur' },
          { max: 255, message: '长度不大于255个字符', trigger: 'blur' }
        ],
        disk: [
          { required: true, message: '请输入硬盘大小', trigger: 'blur' },
          { max: 255, message: '长度不大于255个字符', trigger: 'blur' }
        ],
        gpu: [{ max: 255, message: '长度不大于255个字符', trigger: 'blur' }],
        screen: [
          { required: true, message: '请输入屏幕大小', trigger: 'blur' },
          { max: 255, message: '长度不大于255个字符', trigger: 'blur' }
        ],
        price: [
          { required: true, message: '请输入产品价格', trigger: 'blur' },
          { max: 255, message: '长度不大于255个字符', trigger: 'blur' }
        ],
        suggest_ug: [],
        remarks: []
      }
    }
  },
  created() {
    this.getModels()
  },
  methods: {
    // 添加型号
    addModel() {
      this.$refs.addModelFormRef.validate(async (valid) => {
        if (valid === false) return false
        // 添加型号方法
        console.log(this.addModelForm)
        const { data: res } = await this.$http.post('/api/assets/model', this.addModelForm)
        if (res.code !== 0) return this.$message.error('添加型号失败！')
        this.$message.success('添加型号成功！')
        this.getModels()
      })
    },
    // 选中上级型号发生变化时
    selectModelValueChange(val) {
      if (val === null) {
        this.addModelForm.parent_id = 0
      }
    },
    // 选中型号变化时
    selectModelValueChange2(val) {
      if (val.length !== 3) {
        this.selectModelValue2 = []
        this.$set(this.addParaForm, 'model_id', val[2])
      } else {
        this.$set(this.addParaForm, 'model_id', val[2])
      }
    },
    // 重置
    resetForm() {
      this.$refs.addModelFormRef.resetFields()
    },
    // 获取型号
    async getModels() {
      const { data: res } = await this.$http.get('/api/assets/model')
      this.modelsListData = res.data
      this.total = res.total
      console.log(this.modelsListData)
    },
    // 编辑型号
    editModel(row) {
      this.modelEditForm = JSON.parse(JSON.stringify(row))
      console.log(this.modelEditForm)
      this.dialogModelEditFormVisible = true
    },
    async editSaveModel() {
      const { data: res } = await this.$http.put(`/api/assets/model/${this.modelEditForm.id}`, { model_name: this.modelEditForm.model_name })
      if (res.code !== 0) return this.$message.error('保存失败！')
      this.$message.success('保存成功！')
      this.dialogModelEditFormVisible = false
      this.getModels()
    },
    // 删除
    async delModel(scope) {
      this.idArr = []
      // 获取当前型号及其子型号的id
      this.getDepId(scope.row)
      const { data: res } = await this.$http.delete('/api/assets/model', { data: this.idArr })
      if (res.code !== 0) return this.$message.error('删除失败！')
      this.$message.success('删除成功！')
      scope._self.$refs[`popover-${scope.$index}`].doClose()
      this.getModels()
    },
    // 取消操作
    cancelAction(scope) {
      scope._self.$refs[`popover-${scope.$index}`].doClose()
    },
    // 递归返回数据里面所有的id，包含children中的id
    getDepId(data) {
      if (!data.children) {
        this.idArr.push(parseInt(data.id))
      } else {
        this.idArr.push(parseInt(data.id))
        data.children.forEach((item) => {
          this.getDepId(item)
        })
      }
    },
    // 监听tab卡切换
    handleClickTab(tab, event) {
      if (tab.name === 'parameter') {
        this.getPara()
      }
    },
    // 添加配置 对话框
    addParaDialog() {
      this.dialogAddParaFormVisible = true
    },
    // 添加配置
    async addPara() {
      console.log(this.addParaForm)
      this.$refs.addParaFormRef.validate(async (vali) => {
        console.log(vali)
        if (!vali) return this.$message('表单输入不正确，请检查！')
        const { data: res } = await this.$http.post('/api/assets/parameter', this.addParaForm)
        if (res.code !== 0) return this.$message.error('添加配置失败！')
        // 清空表单
        this.dialogAddParaFormVisible = false
        this.selectModelValue2 = []
        this.$message.success('添加配置成功！')
        this.addParaForm = {}
        this.getPara()
      })
    },
    // 获取所有配置
    async getPara() {
      const { data: res } = await this.$http.get('/api/assets/parameter', { params: this.queryParaInfo })
      this.parameterListData = res.data
      this.paraListTotal = res.total
    },
    // 删除配置
    async delPara(scope) {
      console.log(scope)
      const { data: res } = await this.$http.delete(`/api/assets/parameter/${scope.row.id}`)
      if (res.code !== 0) return this.$message.error('删除失败！')
      this.$message.success('删除成功！')
      scope._self.$refs[`popover-${scope.$index}`].doClose()
      this.getPara()
    },
    // 切换每页显示数量
    handleSizeChange(val) {
      this.queryParaInfo.pagesize = val
      this.getPara()
    },
    // 切换每页显示数量
    handleCurrentChange(val) {
      this.queryParaInfo.pagenum = val
      this.getPara()
    }
  }
}
</script>

<style lang="less" scoped>
.tableRowButton {
  margin-right: 5px;
}

.dialog_padding {
  .el-dialog__body {
    padding: 15px 20px;
  }
}
</style>
